package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.threadLocal.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

//springMvc拦截器
//目的是为了获取token，并解析，然后把用户信息存入到threadLocal对象中
public class WmTokenInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//1.从请求对象中获取token
		String token = request.getHeader("token");
		//2.校验token是否有值，以及是否有效
		Optional<String> optional = Optional.ofNullable(token);
		if (optional.isPresent()) {
			//3.如果有效，则取出用户信息，然后保存到ThreadLocal对象中
			Claims claimsBody = AppJwtUtil.getClaimsBody(token);
			Object id = claimsBody.get("id");
			//然后保存到ThreadLocal对象中
			WmUser wmUser = new WmUser();
			wmUser.setId((Integer) id);
			WmThreadLocalUtil.setWmUser(wmUser);

		}
		//4.放行
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		WmThreadLocalUtil.deleteWmUser();
	}
}
